package kamikazehero.data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import kamikazehero.game.score.GameScore;
import kamikazehero.game.score.ScoreList;

import org.sqlite.JDBC;

public class DatabaseConnection {
	
	private String connectionString;
	private Connection conn;
	
	public DatabaseConnection(String connectionString){
		
		this.connectionString = connectionString;
		try {
			Class.forName("org.sqlite.JDBC");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void getConnection(){
		try {
			conn = DriverManager.getConnection(this.connectionString);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	private void close(){
		try {
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void addScore(GameScore score) throws Exception{
		PreparedStatement statement = null;
		
		this.getConnection();
		
		statement = conn.prepareStatement(PreparedStatements._ADD_SCORE);

		statement.setString(2, score.getName());
		statement.setInt(3, score.getScore());
		statement.setString(4, score.getDate());
		statement.addBatch();
		
		conn.setAutoCommit(false);
		statement.executeBatch();
		conn.setAutoCommit(true);
		
		this.close();
		
	}
	
	public ScoreList getScores() throws SQLException{
		ResultSet results = null;
		Statement statement = null;
		ScoreList scores = null;
		
		this.getConnection();
		statement = conn.createStatement();
		results = statement.executeQuery(PreparedStatements._GET_SCORES);
		
		scores = new ScoreList();
		
		while(results.next()){
			GameScore score = new GameScore();
			
			score.setId(results.getInt("id"));
			score.setName(results.getString("name"));
			score.setScore(results.getInt("score"));
			score.setDate(results.getString("date"));
			
			scores.add(score);
		}
		
		return scores;
	}
	
}
